package com.example.ymm.modules1.service.impl.ms;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.exception.YmException;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.entity.my.ms.PmcMaterialRef;
import com.example.ymm.modules1.mapper.my.ms.PmcMaterialRefMapper;
import com.example.ymm.modules1.service.dto.ms.ImportMaterialRefDto;
import com.example.ymm.modules1.service.dto.ms.PmcMaterialRefQueryCriteria;
import com.example.ymm.modules1.service.ms.PmcMaterialRefService;
import com.example.ymm.util.QueryHelpPlus;
import com.example.ymm.util.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
@DS("slave2")
@DSTransactional
public class PmcMaterialRefServiceImpl extends BaseServiceImpl<PmcMaterialRefMapper, PmcMaterialRef> implements PmcMaterialRefService {

    @Override
    public TableList<PmcMaterialRef> list(PmcMaterialRefQueryCriteria criteria, YmPageDto pageDto) {
        IPage<PmcMaterialRef> page = new Page<PmcMaterialRef>(pageDto.getPage(),pageDto.getPageSize());
        QueryWrapper predicate = QueryHelpPlus.getPredicate(PmcMaterialRef.class, criteria);
        predicate.orderByDesc("create_time");
        baseMapper.selectPage(page, predicate);
        TableList<PmcMaterialRef> tableList=new TableList(page);
        return tableList;
    }

    public List<PmcMaterialRef> queryAll(PmcMaterialRefQueryCriteria criteria) {
        QueryWrapper predicate = QueryHelpPlus.getPredicate(PmcMaterialRef.class, criteria);
        predicate.orderByDesc("create_time");
        List<PmcMaterialRef> result =baseMapper.selectList(predicate);
        return result;
    }

    @Override
    public void importOemMaterialRef(ImportMaterialRefDto dto) {
        List<PmcMaterialRef> list = dto.getList();

        if(list==null || list.size()==0){
            throw new YmException("不能为空!");
        }
        LambdaQueryWrapper<PmcMaterialRef> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PmcMaterialRef::getBuMenName, dto.getBuMenName());
        remove(lambdaQueryWrapper);
        List<PmcMaterialRef> adds=new ArrayList<PmcMaterialRef>();
        list.forEach(pmcMaterialRef->{
            if(UtilValidate.isNotEmpty(pmcMaterialRef.getNo())){
                pmcMaterialRef.setBuMenName(dto.getBuMenName());
                adds.add(pmcMaterialRef);
            }
        });

        saveOrUpdateBatch(adds);
    }
}
